package cn.turboinfo.fuyang.api.provider.common.component.shop.interceptor

import cn.turboinfo.fuyang.api.entity.common.event.WrapperApplicationEvent
import cn.turboinfo.fuyang.api.entity.common.event.shop.ShopGeoChangedEvent
import cn.turboinfo.fuyang.api.provider.common.framework.jpa.interceptor.FlushDirtyInterceptor
import cn.turboinfo.fuyang.api.provider.common.repository.database.shop.HousekeepingShopPO
import org.hibernate.type.Type
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Component
import org.springframework.transaction.support.TransactionSynchronization
import org.springframework.transaction.support.TransactionSynchronizationManager
import java.io.Serializable

/**
 * 门店地理信息处理变更拦截器
 */
@Component
class ShopGeoInterceptor(
    private val applicationContext: ApplicationContext,
) : FlushDirtyInterceptor {

    override fun onFlushDirty(
        entity: Any,
        id: Serializable,
        currentState: Array<Any>,
        previousState: Array<out Any>,
        propertyNames: Array<out String>,
        types: Array<out Type>
    ): Boolean {
        val longitudeIndex = propertyNames.indexOf("longitude")
        val latitudeIndex = propertyNames.indexOf("latitude")

        if (previousState[longitudeIndex] != currentState[longitudeIndex] || previousState[latitudeIndex] != currentState[latitudeIndex]) {
            (entity as HousekeepingShopPO)
                .apply {
                    TransactionSynchronizationManager.registerSynchronization(object : TransactionSynchronization {
                        override fun afterCommit() {
                            applicationContext.publishEvent(
                                WrapperApplicationEvent(
                                    ShopGeoChangedEvent.builder()
                                        .shopId(entity.id)
                                        .build()
                                )
                            )
                        }
                    })
                }
        }

        return false
    }

    override fun isSupported(
        entity: Any,
        id: Serializable,
        currentState: Array<out Any>,
        previousState: Array<out Any>,
        propertyNames: Array<out String>,
        types: Array<out Type>
    ): Boolean {
        return entity is HousekeepingShopPO
    }

}
